//
// Created by mio on 25-5-13.
//

#include "AudioEncoder.h"
#include "AACEncoder.h"

AudioEncoder::AudioEncoder()
{
    AAC_encoder_.reset(new AACEncoder());
}

AudioEncoder::~AudioEncoder()
{
    Close();
}

bool AudioEncoder::Open(int samplerate, int channels, int format, int bitrate_kbps) {
    if (AAC_encoder_->GetAVCodecContext()) return false; // 已初始化完
    AVConfig encoder_config;
    encoder_config.audio.samplerate = samplerate;
    encoder_config.audio.channels = channels;
    encoder_config.audio.format = (AVSampleFormat)format;
    encoder_config.audio.bitrate = bitrate_kbps;

    if(!AAC_encoder_->Open(encoder_config)) return false;
    return true;
}

void AudioEncoder::Close()
{
    channel_ = 0;
    bitrate_ = 0;
    samplerate_ = 0;
    format_ = AV_SAMPLE_FMT_NONE;
    if (AAC_encoder_) {
        AAC_encoder_->Close();
        AAC_encoder_.reset();
        AAC_encoder_ = nullptr;
    }
}

int AudioEncoder::GetFrames()
{
    if (!AAC_encoder_->GetAVCodecContext()) return -1;
    return  AAC_encoder_->GetFrameSamples();
}

int AudioEncoder::GetSpecificConfig(uint8_t *buf, int max_buf_size)
{
    AVCodecContext* codecCtx = AAC_encoder_->GetAVCodecContext();;
    if (!AAC_encoder_->GetAVCodecContext()) return -1;
    memcpy(buf, codecCtx->extradata, codecCtx->extradata_size);
    return codecCtx->extradata_size;
}

AVPacketPtr AudioEncoder::Encode(const uint8_t *pcm, int samples)
{
    if(!AAC_encoder_->GetAVCodecContext()) return nullptr;
    return AAC_encoder_->Encode(pcm, samples);
}
